#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>


int main() {
    int pipe_fd[2] = {0};
    if (pipe(pipe_fd) < 0) {
        perror("pipe");
        return 1;
    }
    printf("%d %d\n", pipe_fd[0], pipe_fd[1]);
    pid_t id = fork();
    if (id < 0) {
        perror("fork");
    }
    if (id == 0) { //write
        //child
        close(pipe_fd[0]);
        char *msg = "hello world, i am child process";
        int count = 5;
        while (count) {
            write(pipe_fd[1], msg, strlen(msg));
            sleep(1);
            count--;
        }
        close(pipe_fd[1]);
        exit(0);
    }else {     // read
        //parent
        close(pipe_fd[1]);
        ssize_t size = 0;
        char buf[64] = {0};
        while(1) {
            size = read(pipe_fd[0], buf, sizeof(buf)-1);
            if (size > 0) {
                buf[size] = 0;
                printf("parent get message from child#: %s\n", buf);
            } else if (size == 0) {
                printf("pipe file close, child quit!\n");
                break;
            }else{
                break;
            }
            close(pipe_fd[0]);
        }
        //close(pipe_fd[0]);
        int status = 0;
        pid_t ret = waitpid(id, &status, 0);
        if (ret == -1) {
            perror("waitpid");
            return 1;
        }
        printf("child is waited, the sig code is %d, the exit code is %d\n", (status & 0x7F), WEXITSTATUS(status));
    }
    return 0;
}
